package cn.tnar.parkservice.service.impl;


import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.controller.system.TParkAccessController;
import cn.tnar.parkservice.exception.CustomException;
import cn.tnar.parkservice.mapper.TAcctBankMerchantInfoMapper;
import cn.tnar.parkservice.mapper.TParkGroupMemberinfoMapper;
import cn.tnar.parkservice.model.dto.MemberinfoMqDto;
import cn.tnar.parkservice.model.dto.SyncMemberDto;
import cn.tnar.parkservice.model.dto.TParkMemberGroupRelationDto;
import cn.tnar.parkservice.model.entity.*;
import cn.tnar.parkservice.model.request.TParkGroupMemberinfoRequest;
import cn.tnar.parkservice.model.response.RecordResponse;
import cn.tnar.parkservice.service.*;
import cn.tnar.parkservice.util.DateUtil1;
import cn.tnar.parkservice.util.DateUtils;
import cn.tnar.parkservice.util.DtoUtil;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import cn.tnar.parkservice.util.common.StringUtil;
import cn.tnar.pms.kesb.KesbException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzb
 * @since 2019-08-20
 */
@Service("tParkGroupMemberinfoServiceImpl")
public class TParkGroupMemberinfoServiceImpl extends ServiceImpl<TParkGroupMemberinfoMapper, TParkGroupMemberinfo> implements ITParkGroupMemberinfoService {
    private ResultJson resultJson = new ResultJson();

    private static final Logger log = LoggerFactory.getLogger(TParkAccessController.class);

    @Autowired
    @Qualifier("tParkGroupCarinfoServiceImpl")
    private ITParkGroupCarinfoService itParkGroupCarinfoService;


    @Autowired
    private ITParkGroupSeatinfoService itParkGroupSeatinfoService;

    @Autowired
    @Qualifier("tParkMemberGroupRelationServiceImpl")
    private ITParkMemberGroupRelationService itParkMemberGroupRelationService;

    @Autowired
    @Qualifier("tParkMemberGroupServiceImpl")
    private ITParkMemberGroupService itParkMemberGroupService;

    @Autowired
    @Qualifier("accessRuleServiceImpl")
    private AccessRuleService accessRuleService;

    @Autowired
    @Qualifier("tSysSnogeneralServiceImpl")
    private ITSysSnogeneralService itSysSnogeneralService;

    @Autowired
    @Qualifier("tParkRegionServiceImpl")
    private ITParkRegionService itParkRegionService;

    @Autowired
    private ITCarMemberamountinfoService itCarMemberamountinfoService;

    @Autowired
    private ITParkGroupOperateLogService itParkGroupOperateLogService;

    @Autowired
    private ITCarFeesroleinfoService itCarFeesroleinfoService;

    @Autowired
    private ITParkInfoService itParkInfoService;

    @Autowired
    private ITAcctCustInfoService itAcctCustInfoService;

    @Autowired
    @Qualifier("kesbAPIService")
    private KesbApiService kesbApiService;


    @Autowired
    private ITTradeTraceOrderService tradeTraceOrderService;

    @Autowired
    private TAcctBankMerchantInfoMapper bankMerchantInfoMapper;

    @Autowired
    private MqService mqService;


    @Override
    @Transactional
    public ResultJson insert(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        //查询子卡下所有t_park_group_memberinfo  id
        List<String> memberIds = itParkMemberGroupRelationService.getMemberIdByChildLook(request.getMemberGroupId());
        String join = String.join(",", memberIds);
        // 查询车牌(含车辆类型)在卡组下是否存在
        if (memberIds.size() > 0) {
            List<Map<String, Object>> list = itParkGroupCarinfoService.checkCarId(request.getCarId(), request.getCarType(), join);
            if (list.size() > 0) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_CAR_EXISTS).setData(null);
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        Long groupMemberinfoId = this.getTableNo(1);
        Long groupCarinfoId = this.getTableNo(2);
        Long operateLogId = this.getTableNo(4);

        TParkGroupMemberinfo tParkGroupMemberinfo = new TParkGroupMemberinfo();
        tParkGroupMemberinfo.setId(groupMemberinfoId);
        tParkGroupMemberinfo.setNodeId(1);
        tParkGroupMemberinfo.setAgentId(request.getAgentId());
        tParkGroupMemberinfo.setParkCode(request.getParkCode());
        tParkGroupMemberinfo.setOwnerName(request.getOwnerName());
        tParkGroupMemberinfo.setTelNo(request.getTelNo());
        tParkGroupMemberinfo.setMemberLevel(1);
        tParkGroupMemberinfo.setStartDate(request.getStartDate());
        tParkGroupMemberinfo.setEndDate(request.getEndDate());
        tParkGroupMemberinfo.setDelflag(1);
        tParkGroupMemberinfo.setCreateTime(Long.valueOf(now));
        tParkGroupMemberinfo.setUpdateTime(Long.valueOf(now));
        tParkGroupMemberinfo.setRemark(request.getRemark() == null ? "" : request.getRemark());

        if (request.getFun() == 0) {
            tParkGroupMemberinfo.setMember_type(2);
        }
        boolean save = this.save(tParkGroupMemberinfo);
        if (!save) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        TParkGroupCarinfo tParkGroupCarinfo = new TParkGroupCarinfo();
        tParkGroupCarinfo.setId(groupCarinfoId);
        tParkGroupCarinfo.setNodeId(0);
        tParkGroupCarinfo.setCarId(request.getCarId());
        tParkGroupCarinfo.setGroupId(groupMemberinfoId);
        tParkGroupCarinfo.setCarType(request.getCarType());
        tParkGroupCarinfo.setCreateTime(Long.valueOf(now));
        tParkGroupCarinfo.setDelflag(1);
        boolean save1 = itParkGroupCarinfoService.save(tParkGroupCarinfo);
        if (!save1) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        TParkMemberGroupRelation tParkMemberGroupRelation = new TParkMemberGroupRelation();
        tParkMemberGroupRelation.setGroupId(request.getMemberGroupId());
        tParkMemberGroupRelation.setCreateTime(Long.valueOf(now));
        tParkMemberGroupRelation.setMemberId(groupMemberinfoId);
        tParkMemberGroupRelation.setUpdateTime(Long.valueOf(now));
        boolean save2 = itParkMemberGroupRelationService.save(tParkMemberGroupRelation);
        if (!save2) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        String operateRemark = "";
        String memberType = "";
        //白名单请求时
        if (request.getFun() == 0) {
            operateRemark = "新增待审核白名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
        }
        //黑名单请求时
        if (request.getFun() == 1) {
            memberType = Constant.MEMBER_TYPE_BLACK;
            operateRemark = "新增黑名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
        }

        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(request.getParkCode())
                .setRegionCode("")
                .setCarId(request.getCarId())
                .setCarType(request.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(1)
                .setOperateDay(0);

        boolean save4 = itParkGroupOperateLogService.save(tParkGroupOperateLog);
        if (!save4) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        if (request.getFun() == 1) {
            //下发黑名单信息
            MemberinfoMqDto dto = new MemberinfoMqDto();
            dto.setCar_id(request.getCarId());
            dto.setCar_type(request.getCarType().toString().replaceAll("8", "5"));
            dto.setEnd_date(request.getEndDate().toString());
            dto.setGroup_id(groupMemberinfoId.toString());
            dto.setId(groupMemberinfoId.toString());
            dto.setMember_type(memberType);
            dto.setOper_type(Constant.OPER_CAR);
            dto.setOwner_name(request.getOwnerName());
            dto.setPark_code(request.getParkCode());
            dto.setRemark(request.getRemark() == null ? "" : request.getRemark());
            dto.setSeat_num("0");
            dto.setSend_time(now);
            dto.setStart_date(request.getStartDate().toString());

            mqService.mqSend(JSON.toJSONString(dto), "member." + request.getParkCode());

            QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", groupMemberinfoId);
            TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
            TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(one, TParkMemberGroupRelationDto.class);
            tParkMemberGroupRelationDto.setType(1);
            //下发关系表
            mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + request.getParkCode());
        }


        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);


    }

    @Override
    public ResultJson check(String json) {
        //groupMemberinfoId  operId  look 0 通过 1 不通过
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        Long groupMemberinfoId = request.getGroupMemberinfoId();
        TParkGroupMemberinfo byId = this.getById(groupMemberinfoId);
        TParkMemberGroupRelation memberGroupRelation = itParkMemberGroupRelationService.getOne(new QueryWrapper<TParkMemberGroupRelation>().eq("member_id", groupMemberinfoId));
        TParkMemberGroup memberGroup = itParkMemberGroupService.getById(memberGroupRelation.getGroupId());
        TParkGroupCarinfo carinfo = itParkGroupCarinfoService.getOne(new QueryWrapper<TParkGroupCarinfo>().eq("group_id", groupMemberinfoId).eq("delflag", 1));
        request.setTelNo(byId.getTelNo());
        request.setOwnerName(byId.getOwnerName());
        request.setStartDate(byId.getStartDate());
        request.setEndDate(byId.getEndDate());
        request.setParkCode(memberGroup.getParkCode());
        request.setCarId(carinfo.getCarId());
        request.setCarType(carinfo.getCarType());
        request.setRemark(byId.getRemark());
        request.setCustId(itParkInfoService.getOne(new QueryWrapper<TParkInfo>().eq("park_code", memberGroup.getParkCode())).getCustId());


        if (request.getLook().equals("1")) {
            Long operateLogId = this.getTableNo(4);
            this.removeById(groupMemberinfoId);
            itParkMemberGroupRelationService.remove(new QueryWrapper<TParkMemberGroupRelation>().eq("member_id", groupMemberinfoId));

            itParkGroupCarinfoService.update(new TParkGroupCarinfo().setDelflag(2), new QueryWrapper<TParkGroupCarinfo>().eq("group_id", groupMemberinfoId));
            String operateRemark = "删除待审核白名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
            TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                    .setId(operateLogId)
                    .setNodeId(0)
                    .setGroupId(groupMemberinfoId)
                    .setSeatId(0L)
                    .setAgentId(0L)
                    .setParkCode(request.getParkCode())
                    .setRegionCode("")
                    .setCarId(request.getCarId())
                    .setCarType(request.getCarType())
                    .setRemark(operateRemark)
                    .setOperateTime(Long.valueOf(now))
                    .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                    .setOperateType(3)
                    .setOperateDay(0);
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
        }


        boolean b = this.updateById(new TParkGroupMemberinfo().setMember_type(1).setId(groupMemberinfoId).setUpdateTime(Long.valueOf(now)));
        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        String operateRemark = "新增白名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
        String memberType = Constant.MEMBER_TYPE_WHITE;
        Long operateLogId = this.getTableNo(4);

        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(request.getParkCode())
                .setRegionCode("")
                .setCarId(request.getCarId())
                .setCarType(request.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(1)
                .setOperateDay(0);

        boolean save4 = itParkGroupOperateLogService.save(tParkGroupOperateLog);
        if (!save4) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Long memberamountinfoId = this.getTableNo(3);
        TCarMemberamountinfo tCarMemberamountinfo = new TCarMemberamountinfo()
                .setId(memberamountinfoId)
                .setNodeId(1)
                .setCustId(request.getCustId() == null ? 0 : request.getCustId())
                .setParkCode(request.getParkCode())
//                    .setCarId(request.getCarId())
                .setAmountType(3)
                .setFeesRoleid(0L)
                .setRoleName("")
                .setMonthValue(new BigDecimal(0))
                .setUpTime(Long.valueOf(now))
                .setAmountNum(new BigDecimal(0))
                .setStartDate(request.getStartDate())
                .setEndDate(request.getEndDate())
                .setOperId(request.getOperId() == null ? 0 : request.getOperId())
                .setRemark(request.getRemark() == null ? "" : request.getRemark())
                .setRegionCode("")
                .setBuyOri(0)
                .setPayId("0")
                .setMemberId(groupMemberinfoId)
                .setSeatId(null);

        boolean save3 = itCarMemberamountinfoService.save(tCarMemberamountinfo);
        if (!save3) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(request.getCarId());
        dto.setCar_type(request.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(request.getEndDate().toString());
        dto.setGroup_id(groupMemberinfoId.toString());
        dto.setId(groupMemberinfoId.toString());
        dto.setMember_type(memberType);
        dto.setOper_type(Constant.OPER_CAR);
        dto.setOwner_name(request.getOwnerName());
        dto.setPark_code(request.getParkCode());
        dto.setRemark(request.getRemark() == null ? "" : request.getRemark());
        dto.setSeat_num("0");
        dto.setSend_time(now);
        dto.setStart_date(request.getStartDate().toString());

        mqService.mqSend(JSON.toJSONString(dto), "member." + request.getParkCode());

        TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(memberGroupRelation, TParkMemberGroupRelationDto.class);
        tParkMemberGroupRelationDto.setType(1);
        //下发关系表
        mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + request.getParkCode());
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }

    @Override
    public ResultJson select(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        List<String> memberIds = itParkMemberGroupRelationService.getMemberIdByChildLook(request.getMemberGroupId());
        Page<Map<String, Object>> page = getMemberinfos(request, memberIds);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
    }


    @Override
    public ResultJson selectOne(String json) {
        TParkGroupMemberinfoRequest request = new TParkGroupMemberinfoRequest();
        request.setMemberinfoIds(json);
        List<Map<String, Object>> list = itParkGroupCarinfoService.selectBaiList(request);

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
    }

    @Override
    public ResultJson stop(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long groupMemberinfoId = request.getGroupMemberinfoId();
        Integer days = request.getDays();
        if (days < 0) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_DAYS_ERROR).setData(null);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        TParkGroupMemberinfo byId = this.getById(groupMemberinfoId);

        if (byId == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBER_ERROR).setData(null);
        }
        String createDate = String.valueOf(byId.getEndDate());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String temp = "";
        try {
            Date date = sdf.parse(createDate);
            Calendar cl = Calendar.getInstance();
            cl.setTime(date);
            cl.add(Calendar.DATE, days);

            temp = sdf.format(cl.getTime());
        } catch (ParseException e) {
            log.error(Constant.ERROR_MSG_DATE, e);
            throw new CustomException(Constant.ERROR_MSG_DATE);
        }
        TParkGroupMemberinfo entity = new TParkGroupMemberinfo();
        entity.setId(Long.valueOf(groupMemberinfoId));
        entity.setCarState(3);
        entity.setEndDate(Integer.parseInt(temp));
        entity.setUpdateTime(Long.valueOf(now));
        boolean b = this.updateById(entity);

        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Long memberamountinfoId = this.getTableNo(3);
        Long operateLogId = this.getTableNo(4);

        TCarMemberamountinfo tCarMemberamountinfo = new TCarMemberamountinfo()
                .setId(memberamountinfoId)
                .setNodeId(1)
                .setCustId(request.getCustId() == null ? 0 : request.getCustId())
                .setParkCode(byId.getParkCode())
                .setAmountType(2)
                .setFeesRoleid(0L)
                .setRoleName("")
                .setMonthValue(new BigDecimal(0))
                .setUpTime(Long.valueOf(now))
                .setAmountNum(new BigDecimal(0))
                .setStartDate(Integer.parseInt(createDate))
                .setEndDate(Integer.parseInt(temp))
                .setOperId(request.getOperId() == null ? 0 : request.getOperId())
                .setRemark(request.getRemark() == null ? "" : request.getRemark())
                .setRegionCode("")
                .setBuyOri(0)
                .setPayId("0")
                .setMemberId(groupMemberinfoId)
                .setSeatId(null);
        try {
            itCarMemberamountinfoService.save(tCarMemberamountinfo);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_AMOUNT, e);
            throw new CustomException(Constant.ERROR_MSG_AMOUNT);
        }


        QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", groupMemberinfoId);
        queryWrapper.eq("delflag", 1);
        TParkGroupCarinfo one = null;
        try {
            one = itParkGroupCarinfoService.getOne(queryWrapper);

        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_CARINFO, e);
            throw new CustomException(Constant.ERROR_MSG_CARINFO);
        }

        String operateRemark = "暂停白名单,手机号:" + byId.getTelNo() + ",车主姓名:" + byId.getOwnerName() + ",到期日期:" + Integer.parseInt(temp);
        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(byId.getParkCode())
                .setRegionCode("")
                .setCarId(one == null ? "" : one.getCarId())
                .setCarType(one == null ? 0 : one.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(7)
                .setOperateDay(days);
        try {
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_GROUPLOG, e);
            throw new CustomException(Constant.ERROR_MSG_GROUPLOG);
        }

        //下发白名单信息
        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(one.getCarId());
        dto.setCar_type(one.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(temp);
        dto.setGroup_id(groupMemberinfoId.toString());
        dto.setId(groupMemberinfoId.toString());
        dto.setMember_type(Constant.MEMBER_TYPE_WHITE);
        dto.setOper_type(Constant.OPER_STOP);
        dto.setOwner_name(byId.getOwnerName());
        dto.setPark_code(byId.getParkCode());
        dto.setRemark(byId.getRemark());
        dto.setSeat_num("0");
        dto.setSend_time(now);
        dto.setStart_date(byId.getStartDate().toString());
        mqService.mqSend(JSON.toJSONString(dto), "member." + byId.getParkCode());

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);


    }

    @Override
    public ResultJson defer(String json) {
        //暂停状态不予延期
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long groupMemberinfoId = request.getGroupMemberinfoId();

        TParkGroupMemberinfo byId = this.getById(groupMemberinfoId);
        if (byId == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBER_ERROR).setData(null);
        }

        QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", groupMemberinfoId);
        queryWrapper.eq("delflag", 1);
        TParkGroupCarinfo one = null;
        try {
            one = itParkGroupCarinfoService.getOne(queryWrapper);

        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_CARINFO, e);
            throw new CustomException(Constant.ERROR_MSG_CARINFO);
        }

        String date = request.getDate();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        TParkGroupMemberinfo entity = new TParkGroupMemberinfo();
        entity.setId(Long.valueOf(groupMemberinfoId));
        entity.setEndDate(Integer.parseInt(date));
        entity.setUpdateTime(Long.valueOf(now));
        boolean b = this.updateById(entity);
        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Long operateLogId = this.getTableNo(4);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date parse = null;
        Date parse1 = null;
        try {
            parse = sdf.parse(byId.getEndDate().toString());
            parse1 = sdf.parse(request.getDate());
        } catch (ParseException e) {
            log.error(Constant.ERROR_MSG_DATE, e);
            e.printStackTrace();
        }
        String operateRemark = "延期白名单,手机号:" + byId.getTelNo() + ",车主姓名:" + byId.getOwnerName() + ",延期日期:" + request.getDate();
        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(byId.getParkCode())
                .setRegionCode("")
                .setCarId(one == null ? "" : one.getCarId())
                .setCarType(one == null ? 0 : one.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(9)
                .setOperateDay(DateUtils.differentDaysByMillisecond(parse, parse1));

        try {
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_GROUPLOG, e);
            throw new CustomException(Constant.ERROR_MSG_GROUPLOG);
        }


        //下发白名单信息
        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(one.getCarId());
        dto.setCar_type(one.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(date);
        dto.setGroup_id(groupMemberinfoId.toString());
        dto.setId(groupMemberinfoId.toString());
        dto.setMember_type(Constant.MEMBER_TYPE_WHITE);
        dto.setOper_type(Constant.OPER_DEFER);
        dto.setOwner_name(byId.getOwnerName());
        dto.setPark_code(byId.getParkCode());
        dto.setRemark(byId.getRemark());
        dto.setSeat_num("0");
        dto.setSend_time(now);
        dto.setStart_date(byId.getStartDate().toString());
        mqService.mqSend(JSON.toJSONString(dto), "member." + byId.getParkCode());

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

    @Override
    @Transactional
    public ResultJson delete(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long groupMemberinfoId = request.getGroupMemberinfoId();

        TParkGroupMemberinfo byId = this.getById(groupMemberinfoId);
        if (byId == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBER_ERROR).setData(null);
        }
        QueryWrapper<TParkGroupCarinfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("group_id", groupMemberinfoId);
        queryWrapper1.eq("delflag", 1);
        TParkGroupCarinfo one = null;
        try {
            one = itParkGroupCarinfoService.getOne(queryWrapper1);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_CARINFO, e);
            throw new CustomException(Constant.ERROR_MSG_CARINFO);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        TParkGroupMemberinfo entity = new TParkGroupMemberinfo();
        entity.setId(Long.valueOf(groupMemberinfoId));
        entity.setDelflag(2);
        entity.setUpdateTime(Long.valueOf(now));

        boolean b = this.updateById(entity);
        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", groupMemberinfoId);
        TParkGroupCarinfo tParkGroupCarinfo = new TParkGroupCarinfo();
        tParkGroupCarinfo.setDelflag(2);
        boolean update = itParkGroupCarinfoService.update(tParkGroupCarinfo, queryWrapper);
        if (!update) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        QueryWrapper<TParkMemberGroupRelation> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("member_id", groupMemberinfoId);
        TParkMemberGroupRelation one1 = itParkMemberGroupRelationService.getOne(queryWrapper2);
        boolean b1 = itParkMemberGroupRelationService.removeById(one1.getId());

        if (!b1) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Long operateLogId = this.getTableNo(4);

        String operateRemark = "删除白名单,手机号:" + byId.getTelNo() + ",车主姓名:" + byId.getOwnerName();
        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(byId.getParkCode())
                .setRegionCode("")
                .setCarId(one.getCarId())
                .setCarType(one.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(3)
                .setOperateDay(0);
        try {
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_GROUPLOG, e);
            throw new CustomException(Constant.ERROR_MSG_GROUPLOG);
        }

        //下发白名单信息
        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(one.getCarId());
        dto.setCar_type(one.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(byId.getEndDate().toString());
        dto.setGroup_id(groupMemberinfoId.toString());
        dto.setId(groupMemberinfoId.toString());
        dto.setMember_type(Constant.MEMBER_TYPE_WHITE);
        dto.setOper_type(Constant.OPER_DELETE);
        dto.setOwner_name(byId.getOwnerName());
        dto.setPark_code(byId.getParkCode());
        dto.setRemark(byId.getRemark());
        dto.setSeat_num("0");
        dto.setSend_time(now);
        dto.setStart_date(byId.getStartDate().toString());
        mqService.mqSend(JSON.toJSONString(dto), "member." + byId.getParkCode());
        TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(one1, TParkMemberGroupRelationDto.class);
        tParkMemberGroupRelationDto.setType(2);
        mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + byId.getParkCode());

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

    @Override
    @Transactional
    public ResultJson start(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long groupMemberinfoId = request.getGroupMemberinfoId();

        TParkGroupMemberinfo byId = this.getById(groupMemberinfoId);
        if (byId == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBER_ERROR).setData(null);
        }
        Integer endDate = byId.getEndDate();

        QueryWrapper<TParkGroupCarinfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("group_id", groupMemberinfoId);
        queryWrapper1.eq("delflag", 1);
        TParkGroupCarinfo one = null;
        try {
            one = itParkGroupCarinfoService.getOne(queryWrapper1);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_CARINFO, e);
            throw new CustomException(Constant.ERROR_MSG_CARINFO);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        String now = format.format(new Date());
        String now1 = sdf.format(new Date());
        TParkGroupMemberinfo entity = new TParkGroupMemberinfo();

        QueryWrapper<TParkGroupOperateLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", groupMemberinfoId);
        queryWrapper.eq("operate_type", 7);
        queryWrapper.orderByDesc("operate_time");
        queryWrapper.last("limit 1");
        TParkGroupOperateLog one1 = itParkGroupOperateLogService.getOne(queryWrapper);
        if (one1 == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Integer operateDay = one1.getOperateDay();
        String operateTime = one1.getOperateTime().toString().substring(0, 8);
        try {
            if (DateUtils.differentDaysByMillisecond(sdf.parse(operateTime), sdf.parse(now1)) < operateDay) {
                Date date = DateUtil1.dateAddOrMinus(sdf.parse(String.valueOf(endDate)), DateUtils.differentDaysByMillisecond(sdf.parse(operateTime), sdf.parse(now1)) - operateDay);
                endDate = Integer.parseInt(sdf.format(date));
                entity.setEndDate(endDate);
            }
        } catch (ParseException e) {
            log.error(Constant.ERROR_MSG_DATE, e);
            throw new CustomException(Constant.ERROR_MSG_DATE);
        }

        entity.setId(Long.valueOf(groupMemberinfoId));
        entity.setCarState(1);
        entity.setUpdateTime(Long.valueOf(now));
        boolean b = this.updateById(entity);

        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        Long memberamountinfoId = this.getTableNo(3);
        Long operateLogId = this.getTableNo(4);

        TCarMemberamountinfo tCarMemberamountinfo = new TCarMemberamountinfo()
                .setId(memberamountinfoId)
                .setNodeId(1)
                .setCustId(request.getCustId() == null ? 0 : request.getCustId())
                .setParkCode(byId.getParkCode())
                .setAmountType(4)
                .setFeesRoleid(0L)
                .setRoleName("")
                .setMonthValue(new BigDecimal(0))
                .setUpTime(Long.valueOf(now))
                .setAmountNum(new BigDecimal(0))
                .setStartDate(0)
                .setEndDate(0)
                .setOperId(request.getOperId() == null ? 0 : request.getOperId())
                .setRemark(request.getRemark() == null ? "" : request.getRemark())
                .setRegionCode("")
                .setBuyOri(0)
                .setPayId("0")
                .setMemberId(groupMemberinfoId)
                .setSeatId(null);


        try {
            itCarMemberamountinfoService.save(tCarMemberamountinfo);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_AMOUNT, e);
            throw new CustomException(Constant.ERROR_MSG_AMOUNT);
        }

        String operateRemark = "启用白名单,手机号:" + byId.getTelNo() + ",车主姓名:" + byId.getOwnerName() + ",到期日期" + endDate;
        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(groupMemberinfoId)
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(byId.getParkCode())
                .setRegionCode("")
                .setCarId(one.getCarId())
                .setCarType(one.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(8)
                .setOperateDay(0);

        try {
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_GROUPLOG, e);
            throw new CustomException(Constant.ERROR_MSG_GROUPLOG);
        }

        //下发白名单信息
        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(one.getCarId());
        dto.setCar_type(one.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(endDate.toString());
        dto.setGroup_id(groupMemberinfoId.toString());
        dto.setId(groupMemberinfoId.toString());
        dto.setMember_type(Constant.MEMBER_TYPE_WHITE);
        dto.setOper_type(Constant.OPER_DEFER);
        dto.setOwner_name(byId.getOwnerName());
        dto.setPark_code(byId.getParkCode());
        dto.setRemark(byId.getRemark());
        dto.setSeat_num("1");
        dto.setSend_time(now);
        dto.setStart_date(byId.getStartDate().toString());
        mqService.mqSend(JSON.toJSONString(dto), "member." + byId.getParkCode());
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

    @Override
    @Transactional
    public ResultJson update(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        //判断是否是原先的车牌及类型
        List<Map<String, Object>> list1 = itParkGroupCarinfoService.checkCarId(request.getCarId(), request.getCarType(), String.valueOf(request.getGroupMemberinfoId()));

        if (list1.size() == 0) {
            List<String> memberIds = itParkMemberGroupRelationService.getMemberIdByChildLook(request.getMemberGroupId());
            String join = String.join(",", memberIds);

            //查询车牌(含车辆类型)在卡组下是否存在
            List<Map<String, Object>> list = itParkGroupCarinfoService.checkCarId(request.getCarId(), request.getCarType(), join);
            if (list.size() > 0) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_CAR_EXISTS).setData(null);
            }
        }


        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        TParkGroupMemberinfo tParkGroupMemberinfo = new TParkGroupMemberinfo();
        tParkGroupMemberinfo.setId(request.getGroupMemberinfoId());
        tParkGroupMemberinfo.setParkCode(request.getParkCode());
        tParkGroupMemberinfo.setOwnerName(request.getOwnerName());
        tParkGroupMemberinfo.setTelNo(request.getTelNo());
        tParkGroupMemberinfo.setStartDate(request.getStartDate());
        tParkGroupMemberinfo.setEndDate(request.getEndDate());
        tParkGroupMemberinfo.setUpdateTime(Long.valueOf(now));
        tParkGroupMemberinfo.setRemark(request.getRemark() == null ? "" : request.getRemark());
        boolean b = this.updateById(tParkGroupMemberinfo);
        if (!b) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
        TParkGroupCarinfo tParkGroupCarinfo = new TParkGroupCarinfo();
        tParkGroupCarinfo.setCarId(request.getCarId());
        tParkGroupCarinfo.setCarType(request.getCarType());
        queryWrapper.eq("group_id", request.getGroupMemberinfoId());
        queryWrapper.eq("delflag", 1);

        boolean update = itParkGroupCarinfoService.update(tParkGroupCarinfo, queryWrapper);
        if (!update) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        Long operateLogId = this.getTableNo(4);

        String operateRemark = "";
        String memberType = "";
        //白名单请求时
        if (request.getFun() == 0) {
            memberType = Constant.MEMBER_TYPE_WHITE;
            operateRemark = "修改白名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
            ;
        }
        if (request.getFun() == 1) {
            memberType = Constant.MEMBER_TYPE_BLACK;
            operateRemark = "修改黑名单,手机号:" + request.getTelNo() + ",车主姓名:" + request.getOwnerName() + ",开始时间:" + request.getStartDate() + ",结束时间:" + request.getEndDate();
            ;
        }
        TParkGroupOperateLog tParkGroupOperateLog = new TParkGroupOperateLog()
                .setId(operateLogId)
                .setNodeId(0)
                .setGroupId(request.getGroupMemberinfoId())
                .setSeatId(0L)
                .setAgentId(0L)
                .setParkCode(request.getParkCode())
                .setRegionCode("")
                .setCarId(request.getCarId())
                .setCarType(request.getCarType())
                .setRemark(operateRemark)
                .setOperateTime(Long.valueOf(now))
                .setOperatorNo(request.getOperId() == null ? "" : request.getOperId().toString())
                .setOperateType(2)
                .setOperateDay(0);
        try {
            itParkGroupOperateLogService.save(tParkGroupOperateLog);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_GROUPLOG, e);
            throw new CustomException(Constant.ERROR_MSG_GROUPLOG);
        }

        //下发白名单信息
        MemberinfoMqDto dto = new MemberinfoMqDto();
        dto.setCar_id(request.getCarId());
        dto.setCar_type(request.getCarType().toString().replaceAll("8", "5"));
        dto.setEnd_date(request.getEndDate().toString());
        dto.setGroup_id(request.getGroupMemberinfoId().toString());
        dto.setId(request.getGroupMemberinfoId().toString());
        dto.setMember_type(memberType);
        dto.setOper_type(Constant.OPER_UPDATE);
        dto.setOwner_name(request.getOwnerName());
        dto.setPark_code(request.getParkCode());
        dto.setRemark(request.getRemark());
        dto.setSeat_num("0");
        dto.setSend_time(now);
        dto.setStart_date(request.getStartDate().toString());
        mqService.mqSend(JSON.toJSONString(dto), "member." + request.getParkCode());

        dto.setOper_type(Constant.OPER_DEFER);
        mqService.mqSend(JSON.toJSONString(dto), "member." + request.getParkCode());

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

    @Override
    public ResultJson queryAll(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        List<String> memberIdByParent = itParkMemberGroupRelationService.getMemberIdByParent(request.getMemberGroupId());
        Page<Map<String, Object>> page = getMemberinfos(request, memberIdByParent);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
    }

    @Override
    public ResultJson queryOtherAll(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        TParkMemberGroup byId = itParkMemberGroupService.getById(request.getMemberGroupId());
        List<String> memberIds = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> page = new ArrayList<>();
        if (byId.getType().compareTo(new Integer(1)) == 0) {
            memberIds = itParkMemberGroupRelationService.getMemberIdByChildLook(request.getMemberGroupId());
            page = getOtherMemberinfos(request, memberIds);

            TCarFeesroleinfo byId1 = itCarFeesroleinfoService.getById(byId.getFeesroleinfoId() == null ? 0 : byId.getFeesroleinfoId());
            for (Map<String, Object> map : page) {
                map.put("role_name", byId1 == null ? "" : byId1.getRoleName());
            }
            list.addAll(page);
        } else {
            List<String> strings = itParkMemberGroupService.selectByParentId(new ArrayList<>(), request.getMemberGroupId());

            for (String s : strings) {
                memberIds = itParkMemberGroupRelationService.getMemberIdByChildLook(Long.valueOf(s));
                page = getOtherMemberinfos(request, memberIds);
                TParkMemberGroup tParkMemberGroup = itParkMemberGroupService.getById(s);
                TCarFeesroleinfo byId1 = itCarFeesroleinfoService.getById(tParkMemberGroup.getFeesroleinfoId() == null ? 0 : tParkMemberGroup.getFeesroleinfoId());
                for (Map<String, Object> map : page) {
                    map.put("role_name", byId1 == null ? "" : byId1.getRoleName());
                    list.add(map);
                }

            }

        }
        Page page1 = this.byPage(request.getPageNo(), request.getPageSize(), list);

        List records = page1.getRecords();

        for (int i = 0; i < records.size(); i++) {
            int count = 0;
            for (int j = 0; j < records.size(); j++) {
                if (((Map) records.get(i)).get("memberinfo_id").toString().equals(((Map) records.get(j)).get("memberinfo_id").toString())) {
                    count++;
                }
            }
            ((Map) records.get(i)).put("count", count);
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page1);
    }


    private List<Map<String, Object>> getOtherMemberinfos(TParkGroupMemberinfoRequest request, List<String> memberIds) {

        List<Map<String, Object>> list = new ArrayList<>();
        if (memberIds.size() > 0) {
            request.setMemberinfoIds(String.join(",", memberIds));
            list = itParkGroupCarinfoService.selectMemberList(request);
        }

        return list;
    }

    private Long getTableNo(Integer num) {
        Long id = null;
        try {
            if (num == 1) {
                //  groupMemberinfoId
                id = itSysSnogeneralService.GetNextSno(500);
            }
            if (num == 2) {
                // groupCarinfoId
                id = itSysSnogeneralService.GetNextSno(501);
            }
            if (num == 3) {
                // memberamountinfoId
                id = itSysSnogeneralService.GetNextSno(53);
            }
            if (num == 4) {
                // operateLogId
                id = itSysSnogeneralService.GetNextSno(504);
            }

        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_SNO, e);
            throw new CustomException(Constant.ERROR_MSG_SNO);
        }
        return id;
    }


    private Page<Map<String, Object>> getMemberinfos(TParkGroupMemberinfoRequest request, List<String> memberIds) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (memberIds.size() > 0) {
            request.setMemberinfoIds(String.join(",", memberIds));
            list = itParkGroupCarinfoService.selectBaiList(request);
        }
        for (Map<String, Object> map : list) {
            QueryWrapper<TParkMemberGroupRelation> relationQueryWrapper = new QueryWrapper<>();
            relationQueryWrapper.eq("member_id", map.get("groupMemberinfoId").toString());
            TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(relationQueryWrapper);

            TParkMemberGroup byId = itParkMemberGroupService.getById(one.getGroupId());
            String regionCodes = "";
            String regionNames = "";
            if (byId.getAccessRuleId() != null) {
                QueryWrapper<AccessRule> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("access_rule_id", byId.getAccessRuleId());
                List<AccessRule> list1 = accessRuleService.list(queryWrapper);

                List<String> regioncodeList = list1.stream().map(AccessRule::getRegionCode).collect(Collectors.toList());
                regionCodes = String.join(",", regioncodeList);

                if (StringUtils.isNotEmpty(regionCodes)) {
                    List<String> regionnameList = itParkRegionService.getName(regionCodes);
                    regionNames = String.join(",", regionnameList);
                }


                map.put("regionCodes", regionCodes);
                map.put("regionNames", regionNames);
            }
        }

        Page page = byPage(request.getPageNo(), request.getPageSize(), list);
        return page;
    }

    private Page byPage(int pageNo, int count, List list) {
        //总条数
        int size = list.size();
        Page<Map<String, Object>> page = new Page<>(pageNo, count);
        int pageCount = size / count;
        int fromIndex = count * (pageNo - 1);
        int toIndex = fromIndex + count;
        if (toIndex >= size) {
            toIndex = size;
        }
        if (pageNo > pageCount + 1) {
            fromIndex = 0;
            toIndex = 0;
        }
        //设置总条数，默认得到插件的pages
        page.setTotal(size);
        return page.setRecords(list.subList(fromIndex, toIndex));
    }

    @Override
    public ResultJson insertMember(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        LinkedHashMap<String, Object> map1 = new LinkedHashMap<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            List<Map<String, String>> list = new ArrayList<>();
            if (key.contains("member_info")) {
                try {
                    log.info("insertMember-新增会员:c接口请求参数,param======>" + JSON.parseObject(entry.getValue().toString()));
                    list = kesbApiService.queryKesbApiList(Constant.MEMBER_INFO, JSON.parseObject(entry.getValue().toString()));
                    log.info("insertMember-新增会员:c接口返回参数,param======>" + list);
                    map1.put("member_type", JSON.parseObject(entry.getValue().toString()).get("member_type").toString());
                    ResultJson result = checkReturn(list, map1, key);
                    if (result == null) {
                        continue;
                    } else {
                        return result;
                    }
                } catch (KesbException e) {
                    rollBack(map1);
                    return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
                } catch (Exception e) {
                    log.error(Constant.ERROR_MSG_INSERT_MEMBER, e);
                    rollBack(map1);
                    throw new CustomException(Constant.ERROR_MSG_INSERT_MEMBER);
                }
            }
            if (key.contains("carid_info")) {
                JSONObject object = JSON.parseObject(entry.getValue().toString());
                object.put("group_id", map1.get("member_info").toString());
                try {
                    log.info("insertMember-新增车牌:c接口请求参数,param======>" + object);
                    list = kesbApiService.queryKesbApiList(Constant.MEMBER_CARID, object);
                    log.info("insertMember-新增车牌:c接口返回参数,param======>" + list);
                    ResultJson result = checkReturn(list, map1, key);
                    if (result == null) {
                        continue;
                    } else {
                        return result;
                    }
                } catch (KesbException e) {
                    rollBack(map1);
                    return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
                } catch (Exception e) {
                    log.error(Constant.ERROR_MSG_INSERT_CARID, e);
                    rollBack(map1);
                    throw new CustomException(Constant.ERROR_MSG_INSERT_CARID);
                }
            }
            if (key.contains("seat_info")) {
                try {
                    JSONObject object = JSON.parseObject(entry.getValue().toString());
                    object.put("group_id", map1.get("member_info").toString());
                    log.info("insertMember-新增车位:c接口请求参数,param======>" + object);
                    list = kesbApiService.queryKesbApiList(Constant.MEMBER_SEAT, object);
                    log.info("insertMember-新增车位:c接口返回参数,param======>" + list);
                    ResultJson result = checkReturn(list, map1, key);
                    if (result == null) {
                        continue;
                    } else {
                        return result;
                    }
                } catch (KesbException e) {
                    rollBack(map1);
                    return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
                } catch (Exception e) {
                    log.error(Constant.ERROR_MSG_INSERT_SEAT, e);
                    rollBack(map1);
                    throw new CustomException(Constant.ERROR_MSG_INSERT_SEAT);
                }
            }
        }

        Long member_info_id = Long.valueOf(map1.get("member_info").toString());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        TParkMemberGroupRelation tParkMemberGroupRelation = new TParkMemberGroupRelation();
        tParkMemberGroupRelation.setGroupId(Long.valueOf(map.get("memberGroupId").toString()));
        tParkMemberGroupRelation.setCreateTime(Long.valueOf(now));
        tParkMemberGroupRelation.setMemberId(member_info_id);
        tParkMemberGroupRelation.setUpdateTime(Long.valueOf(now));
        boolean save = itParkMemberGroupRelationService.save(tParkMemberGroupRelation);

        if (save) {
            if (("1").equals(map1.get("member_type"))) {
                newMemberMq(String.valueOf(member_info_id), Constant.OPER_CAR, 1, false);
            }

            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
        } else {
            rollBack(map1);
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

    }


    private void rollBack(LinkedHashMap<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            if (key.contains("member_info")) {
                this.removeById(entry.getValue().toString());
                QueryWrapper<TParkGroupOperateLog> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("group_id", entry.getValue().toString());
                itParkGroupOperateLogService.remove(queryWrapper);

                QueryWrapper<TCarMemberamountinfo> carMemberamountinfoQueryWrapper = new QueryWrapper<>();
                carMemberamountinfoQueryWrapper.eq("member_id", entry.getValue().toString());
                itCarMemberamountinfoService.remove(carMemberamountinfoQueryWrapper);
            }
            if (key.contains("carid_info")) {

                itParkGroupCarinfoService.removeById(entry.getValue().toString());
            }
            if (key.contains("seat_info")) {
                itParkGroupSeatinfoService.removeById(entry.getValue().toString());
            }
        }
    }

    private ResultJson checkReturn(List<Map<String, String>> list, LinkedHashMap<String, Object> map, String key) {
        String id = "";
        if (list.get(0).containsKey("id")) {
            id = list.get(0).get("id").toString();
        } else if (list.get(0).containsKey("group_id")) {
            id = list.get(0).get("group_id").toString();
        }

        if (StringUtils.isBlank(id)) {
            rollBack(map);
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        } else {
            map.put(key, id);
            return null;
        }
    }


    @Override
    public ResultJson updateMember(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);

        try {
            log.info("updateMember:c接口请求参数,param======>" + map);
            List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_UPDATE, map);
            log.info("updateMember:c接口返回参数,param======>" + maps);
            newMemberMq(map.get("group_id").toString(), Constant.OPER_UPDATE, 0, false);
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
        } catch (KesbException e) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_UPDATENEW, e);
            throw new CustomException(Constant.ERROR_MSG_UPDATENEW);
        }
    }


    @Override
    public ResultJson deleteMemberSeat(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }

        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> map = JSON.parseObject(array.getJSONObject(i).toString(), Map.class);
            try {
                log.info("deleteMemberSeat:c接口请求参数,param======>" + map);
                List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_DELETE_SEAT, map);
                log.info("deleteMemberSeat:c接口返回参数,param======>" + maps);
                newMemberMq(map.get("group_id").toString(), Constant.OPER_DELETE, 0, true);
                //删除最后一个车位时 即是删除会员 需要解绑子卡会员
                TParkGroupMemberinfo group_id = this.getById(map.get("group_id").toString());
                if (group_id.getDelflag().compareTo(new Integer(2)) == 0) {
                    QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("member_id", map.get("group_id").toString());

                    TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
                    TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(one, TParkMemberGroupRelationDto.class);
                    tParkMemberGroupRelationDto.setType(2);

                    boolean remove = itParkMemberGroupRelationService.remove(queryWrapper);
                    //下发解绑关系表
                    mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + group_id.getParkCode());
                }
            } catch (KesbException e) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
            } catch (Exception e) {
                log.error(Constant.ERROR_MSG_DELETE_SEAT, e);
                throw new CustomException(Constant.ERROR_MSG_DELETE_SEAT);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

    @Override
    public ResultJson queryMemberCarId(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        try {
            log.info("queryMemberCarId:c接口请求参数,param======>" + map);
            List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_SELECT_CARID, map);

            log.info("queryMemberCarId:c接口返回参数,param======>" + maps);
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
        } catch (KesbException e) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_SELECT_CARID, e);
            throw new CustomException(Constant.ERROR_MSG_SELECT_CARID);
        }
    }

    /*  @Override
      public ResultJson checkMemberCarId(String json) {
          Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
          try {
              List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_CHECK_CARID, map);
              return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
          } catch (KesbException e) {
              return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
          } catch (Exception e) {
              log.error(Constant.ERROR_MSG_CHECK_CARID, e);
              throw new CustomException(Constant.ERROR_MSG_CHECK_CARID);
          }
      }*/
    @Override
    public ResultJson checkMemberCarId(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);

        String member_group_id = map.get("member_group_id").toString();
        String car_id = map.get("car_id").toString();
        String car_type = map.get("car_type").toString();

        List<String> memberIdByChild = itParkMemberGroupRelationService.getMemberIdByChild(Long.valueOf(member_group_id));
        for (String memberId : memberIdByChild) {
            QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id", memberId);
            queryWrapper.eq("car_id", car_id);
            queryWrapper.eq("car_type", car_type);
            queryWrapper.eq("delflag", 1);
            List<TParkGroupCarinfo> list = itParkGroupCarinfoService.list(queryWrapper);
            if (list.size() > 0) {
                return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(1);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(0);

    }

    @Override
    public ResultJson deleteMemberCarId(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        try {
            log.info("deleteMemberCarId:c接口请求参数,param======>" + map);
            List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_DELETE_CARID, map);
            log.info("deleteMemberCarId:c接口返回参数,param======>" + maps);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String now = format.format(new Date());
            String member_info_id = map.get("group_id").toString();
            TParkGroupMemberinfo member_info = this.getById(member_info_id);
            QueryWrapper<TParkGroupSeatinfo> qw1 = new QueryWrapper<>();
            qw1.eq("member_id", member_info_id);
            qw1.eq("car_state", 1);
            int count = itParkGroupSeatinfoService.count(qw1);
            QueryWrapper<TParkGroupCarinfo> qw = new QueryWrapper<>();
            qw.eq("group_id", member_info_id);
            qw.eq("car_id", map.get("car_id").toString());
            qw.eq("car_type", map.get("car_type").toString());
            qw.eq("delflag", 2);
            TParkGroupCarinfo one = itParkGroupCarinfoService.getOne(qw);

            MemberinfoMqDto dto = new MemberinfoMqDto();
            dto.setCar_id(map.get("car_id").toString());
            dto.setCar_type(map.get("car_type").toString().replaceAll("8", "5"));
            dto.setEnd_date(member_info.getEndDate().toString());
            dto.setGroup_id(member_info_id);
            //carinfo id
            dto.setId(one.getId().toString());
            dto.setMember_type(Constant.MEMBER_TYPE_NEW);
            dto.setOper_type(Constant.OPER_DELETE);
            dto.setOwner_name(member_info.getOwnerName());
            dto.setPark_code(member_info.getParkCode());
            dto.setRemark(member_info.getRemark() == null ? "" : member_info.getRemark());
            dto.setSeat_num(String.valueOf(count));
            dto.setSend_time(now);
            dto.setStart_date(member_info.getStartDate().toString());
            mqService.mqSend(JSON.toJSONString(dto), "member." + member_info.getParkCode());

            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
        } catch (KesbException e) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_DELETE_CARID, e);
            throw new CustomException(Constant.ERROR_MSG_DELETE_CARID);
        }
    }

    @Override
    public ResultJson insertMemberCarId(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        try {
            log.info("insertMemberCarId:c接口请求参数,param======>" + map);
            List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_CARID, map);
            log.info("insertMemberCarId:c接口返回参数,param======>" + maps);

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String now = format.format(new Date());
            String member_info_id = map.get("group_id").toString();
            TParkGroupMemberinfo member_info = this.getById(member_info_id);
            QueryWrapper<TParkGroupSeatinfo> qw1 = new QueryWrapper<>();
            qw1.eq("member_id", member_info_id);
            qw1.eq("car_state", 1);
            int count = itParkGroupSeatinfoService.count(qw1);

            TParkGroupCarinfo one = itParkGroupCarinfoService.getById(maps.get(0).get("id"));

            MemberinfoMqDto dto = new MemberinfoMqDto();
            dto.setCar_id(map.get("car_id").toString());
            dto.setCar_type(map.get("car_type").toString().replaceAll("8", "5"));
            dto.setEnd_date(member_info.getEndDate().toString());
            dto.setGroup_id(member_info_id);
            //carinfo id
            dto.setId(one.getId().toString());
            dto.setMember_type(Constant.MEMBER_TYPE_NEW);
            dto.setOper_type(Constant.OPER_CAR);
            dto.setOwner_name(member_info.getOwnerName());
            dto.setPark_code(member_info.getParkCode());
            dto.setRemark(member_info.getRemark() == null ? "" : member_info.getRemark());
            dto.setSeat_num(String.valueOf(count));
            dto.setSend_time(now);
            dto.setStart_date(member_info.getStartDate().toString());
            mqService.mqSend(JSON.toJSONString(dto), "member." + member_info.getParkCode());

            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
        } catch (KesbException e) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
        } catch (Exception e) {
            log.error(Constant.ERROR_MSG_INSERT_CARID, e);
            throw new CustomException(Constant.ERROR_MSG_INSERT_CARID);
        }
    }

    @Override
    public ResultJson updateMemberCarId(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }
        ResultJson resultJson = deleteMemberCarId(JSON.toJSONString(array.getJSONObject(0)));
        if (resultJson.getCode().compareTo(200) == 0) {
            ResultJson resultJson1 = insertMemberCarId(JSON.toJSONString(array.getJSONObject(1)));
            return resultJson1;
        } else {
            return resultJson;
        }
    }

    @Override
    public ResultJson queryMemberSeat(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        String group_id = String.valueOf(map.get("group_id"));
        String[] split = group_id.split(",");
        List<Map<String, String>> retMap = new LinkedList<>();
        for (int i = 0; i < split.length; i++) {
            map.put("group_id", split[i]);
            try {
                log.info("queryMemberSeat:c接口请求参数,param======>" + map);
                List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_SELECT_SEAT, map);
                log.info("queryMemberSeat:c接口返回参数,param======>" + maps);
                retMap.addAll(maps);
            } catch (KesbException e) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
            } catch (Exception e) {
                log.error(Constant.ERROR_MSG_SELECT_SEAT, e);
                throw new CustomException(Constant.ERROR_MSG_SELECT_SEAT);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(retMap);

    }

    @Override
    public ResultJson insertMemberSeat(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }
        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> map = JSON.parseObject(array.getJSONObject(i).toString(), LinkedHashMap.class);
            try {
                log.info("insertMemberSeat:c接口请求参数,param======>" + map);
                List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_SEAT, map);
                log.info("insertMemberSeat:c接口返回参数,param======>" + maps);
                if (("1").equals(map.get("member_type"))) {
                    newMemberMq(map.get("group_id").toString(), Constant.OPER_INSERT, 0, false);
                }

            } catch (KesbException e) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
            } catch (Exception e) {
                log.error(Constant.ERROR_MSG_SELECT_SEAT, e);
                throw new CustomException(Constant.ERROR_MSG_SELECT_SEAT);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }

    @Override
    public ResultJson stopMemberSeat(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }
        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> map = JSON.parseObject(array.getJSONObject(i).toString(), LinkedHashMap.class);
            try {
                log.info("stopMemberSeat:c接口请求参数,param======>" + map);
                List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_STOP_SEAT, map);
                log.info("stopMemberSeat:c接口返回参数,param======>" + maps);
                newMemberMq(map.get("group_id").toString(), Constant.OPER_STOP, 0, false);

            } catch (KesbException e) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
            } catch (Exception e) {
                log.error(Constant.ERROR_MSG_STOP_SEAT, e);
                throw new CustomException(Constant.ERROR_MSG_STOP_SEAT);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }

    @Override
    public ResultJson startMemberSeat(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }
        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> map = JSON.parseObject(array.getJSONObject(i).toString(), Map.class);
            try {
                log.info("startMemberSeat:c接口请求参数,param======>" + map);
                List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_START_SEAT, map);
                log.info("startMemberSeat:c接口返回参数,param======>" + maps);
                newMemberMq(map.get("group_id").toString(), Constant.OPER_DEFER, 0, false);

            } catch (KesbException e) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
            } catch (Exception e) {
                log.error(Constant.ERROR_MSG_START_SEAT, e);
                throw new CustomException(Constant.ERROR_MSG_START_SEAT);
            }

        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);

    }

//    @Override
//    public ResultJson deferMemberSeat(String json) {
//        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
//        try {
//            List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_DEFER_SEAT, map);
//
//            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(maps);
//        } catch (KesbException e) {
//            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
//        } catch (Exception e) {
//            log.error(Constant.ERROR_MSG_DEFER_SEAT, e);
//            throw new CustomException(Constant.ERROR_MSG_DEFER_SEAT);
//        }
//
//    }

    @Override
    public ResultJson deferConfirmMemberSeat(String json) {
        String newJson = json.replaceAll("\\\\", "").replaceAll("\"\\[", "\\[").replaceAll("\\]\"", "\\]");
        JSONArray array = new JSONArray();
        try {
            array = JSON.parseObject(newJson, JSONArray.class);
        } catch (Exception e) {
            JSONObject object = JSON.parseObject(newJson, JSONObject.class);
            array.add(object);
        }
        for (int i = 0; i < array.size(); i++) {
            Map<String, Object> map = JSON.parseObject(array.getJSONObject(i).toString(), Map.class);
            if (map.get("new_start_date") != null) {
                try {
                    log.info("deferConfirmMemberSeat:c接口请求参数,param======>" + map);
                    List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_DEFER_SEAT_CONFIRM, map);
                    log.info("deferConfirmMemberSeat:c接口返回参数,param======>" + maps);
                    newMemberMq(map.get("group_id").toString(), Constant.OPER_DEFER, 0, false);
                    //延期插入会员变更表
                    insertAmountRecord(map);
                } catch (KesbException e) {
                    return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
                } catch (Exception e) {
                    log.error(Constant.ERROR_MSG_DEFER_SEAT, e);
                    throw new CustomException(Constant.ERROR_MSG_DEFER_SEAT);
                }
            }

        }
        //Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }

    public void insertAmountRecord(Map<String, Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        String seatId = map.get("id").toString();
        String buyNum = map.get("buy_num") == null ? "1" : String.valueOf(map.get("buy_num"));
        String memberinfoId = map.get("group_id").toString();
        Long fees_roleid = Long.valueOf(map.get("fees_roleid").toString());
        TCarFeesroleinfo tCarFeesroleinfo = itCarFeesroleinfoService.getById(fees_roleid);

        QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberinfoId);
        TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
        Long memberGroupId = one.getGroupId();
        String parkCode = itParkMemberGroupService.getById(memberGroupId).getParkCode();

        QueryWrapper<TParkInfo> infoQueryWrapper = new QueryWrapper<>();
        infoQueryWrapper.eq("park_code", parkCode);
        TParkInfo tParkInfo = itParkInfoService.getOne(infoQueryWrapper);

        Long memberamountinfoId = this.getTableNo(3);

        TCarMemberamountinfo tCarMemberamountinfo = new TCarMemberamountinfo();
        tCarMemberamountinfo.setId(memberamountinfoId);
        tCarMemberamountinfo.setNodeId(1);
        tCarMemberamountinfo.setCustId(tParkInfo.getCustId());
        tCarMemberamountinfo.setParkCode(parkCode);
        tCarMemberamountinfo.setAmountType(5);
        tCarMemberamountinfo.setFeesRoleid(fees_roleid);
        tCarMemberamountinfo.setRoleName(tCarFeesroleinfo.getRoleName());
        tCarMemberamountinfo.setMonthValue(tCarFeesroleinfo.getMonthValue());
        tCarMemberamountinfo.setUpTime(Long.valueOf(now));
        tCarMemberamountinfo.setAmountNum(tCarFeesroleinfo.getMonthValue().multiply(new BigDecimal(buyNum)));
        tCarMemberamountinfo.setStartDate(Integer.valueOf(map.get("new_start_date").toString()));
        tCarMemberamountinfo.setEndDate(Integer.valueOf(map.get("new_end_date").toString()));
        tCarMemberamountinfo.setOperId(Long.valueOf(map.get("operator").toString()));
        tCarMemberamountinfo.setRemark("");
        tCarMemberamountinfo.setRegionCode("");
        tCarMemberamountinfo.setBuyOri(0);
        tCarMemberamountinfo.setPayId("0");
        tCarMemberamountinfo.setMemberId(Long.valueOf(memberinfoId));
        tCarMemberamountinfo.setSeatId(Long.valueOf(seatId));
    }


    @Override
    @Transactional
    public ResultJson changeMemberGroup(String json) {
        Map<String, Object> map = JSON.parseObject(json, LinkedHashMap.class);
        if (map.get("memberGroupId") == null || ("").equals(map.get("memberGroupId"))) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBERGROUP_NULL).setData(null);
        }
        if (map.get("memberinfoId") == null || ("").equals(map.get("memberinfoId"))) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_MEMBERINFOID_NULL).setData(null);
        }
        if (map.get("currentMemberGroupId") == null || ("").equals(map.get("currentMemberGroupId"))) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_CURRENTMEMBERGROUP_NULL).setData(null);
        }
        //当前卡组的计费
//        String currentMemberGroupId = map.get("currentMemberGroupId").toString();
//        TParkMemberGroup currentById = itParkMemberGroupService.getById(currentMemberGroupId);
//        Long currentFeesroleinfoId = currentById.getFeesroleinfoId();
//        TCarFeesroleinfo byId = itCarFeesroleinfoService.getById(currentFeesroleinfoId);
//        BigDecimal monthValue = byId.getMonthValue();

        //转移至卡组的计费
        String memberGroupId = map.get("memberGroupId").toString();
        TParkMemberGroup byIdTo = itParkMemberGroupService.getById(memberGroupId);
        Long toFeesroleinfoId = byIdTo.getFeesroleinfoId();
        if (toFeesroleinfoId == null) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_FEEROLEID_NULL).setData(null);
        }
       /* TCarFeesroleinfo byId2 = itCarFeesroleinfoService.getById(toFeesroleinfoId);
        String roleName1 = byId2.getRoleName();
        BigDecimal monthValue1 = byId2.getMonthValue();

        if (monthValue.compareTo(monthValue1) != 0) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_FEEROLEID_MONEY).setData(null);
        }*/

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        String[] memberinfoIds = map.get("memberinfoId").toString().split(",");
        for (int i = 0; i < memberinfoIds.length; i++) {
            QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
            TParkMemberGroupRelation entity = new TParkMemberGroupRelation();
            entity.setGroupId(Long.valueOf(map.get("memberGroupId").toString()));
            entity.setUpdateTime(Long.valueOf(now));
            queryWrapper.eq("member_id", Long.valueOf(memberinfoIds[i]));
            boolean update = itParkMemberGroupRelationService.update(entity, queryWrapper);
            if (!update) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
            } else {
                TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
                TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(one, TParkMemberGroupRelationDto.class);
                tParkMemberGroupRelationDto.setType(3);
                //下发关系表
                mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + byIdTo.getParkCode());

            }
        }

       /* //转移的计费id不一致时  更新会员变更表以及seatinfo表 feeroleid
        if (toFeesroleinfoId.longValue() != currentFeesroleinfoId.longValue()) {
            for (int i = 0; i < memberinfoIds.length; i++) {
                QueryWrapper<TCarMemberamountinfo> tCarMemberamountinfoQueryWrapper = new QueryWrapper<>();
                tCarMemberamountinfoQueryWrapper.eq("member_id", memberinfoIds[i]);
                TCarMemberamountinfo tCarMemberamountinfo = new TCarMemberamountinfo();
                tCarMemberamountinfo.setFeesRoleid(toFeesroleinfoId);
                tCarMemberamountinfo.setRoleName(roleName1);
                boolean update = itCarMemberamountinfoService.update(tCarMemberamountinfo, tCarMemberamountinfoQueryWrapper);
                if (!update) {
                    log.error(Constant.ERROR_MSG_FEEROLEID_AMOUNT);
                    return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
                }
                QueryWrapper<TParkGroupSeatinfo> tParkGroupSeatinfoQueryWrapper = new QueryWrapper<>();
                tParkGroupSeatinfoQueryWrapper.eq("member_id", memberinfoIds[i]);
                TParkGroupSeatinfo tParkGroupSeatinfo = new TParkGroupSeatinfo();
                tParkGroupSeatinfo.setFeesRoleid(toFeesroleinfoId);
                boolean update1 = itParkGroupSeatinfoService.update(tParkGroupSeatinfo, tParkGroupSeatinfoQueryWrapper);
                if (!update1) {
                    log.error(Constant.ERROR_MSG_FEEROLEID_SEAT);
                    return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
                }

            }

        }*/

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }


    @Override
    public ResultJson weChatSelect(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long memberGroupId = request.getMemberGroupId() != null ? request.getMemberGroupId() : 0;
        String telNo = request.getTelNo();
        if (StringUtil.isBlank(telNo) && memberGroupId == 0) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        List<Map<String, Object>> list = baseMapper.weChatSelect(telNo, request.getCarId(), memberGroupId);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).get("carId") == null) {
                QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("group_id", list.get(i).get("memberInfoId").toString());
                queryWrapper.eq("delflag", 1);
                List<TParkGroupCarinfo> carinfoList = itParkGroupCarinfoService.list(queryWrapper);
                List<String> regioncodeList = carinfoList.stream().map(TParkGroupCarinfo::getCarId).collect(Collectors.toList());
                list.get(i).put("carId", String.join(",", regioncodeList));
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
    }


    public Map<String, Object> queryInfo(Long memberGroupId, Long memberInfoId) {
        List<Map<String, Object>> list = baseMapper.weChatSelect("", "", memberGroupId);
        QueryWrapper<TParkGroupCarinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", memberInfoId);
        queryWrapper.eq("delflag", 1);
        List<TParkGroupCarinfo> carinfoList = itParkGroupCarinfoService.list(queryWrapper);
        List<String> regioncodeList = carinfoList.stream().map(TParkGroupCarinfo::getCarId).collect(Collectors.toList());
        list.get(0).put("carId", String.join(",", regioncodeList));
        return list.get(0);
    }

    @Override
    public ResultJson weChatSelectInfo(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Long groupMemberinfoId = request.getGroupMemberinfoId();
        Long memberGroupId = request.getMemberGroupId();
        if (groupMemberinfoId == 0 && memberGroupId == 0) {
            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG).setData("");
        }
        Map<String, Object> queryInfo = this.queryInfo(memberGroupId, groupMemberinfoId);
        QueryWrapper<TParkGroupSeatinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", groupMemberinfoId);
        List<TParkGroupSeatinfo> seatinfoList = itParkGroupSeatinfoService.list(queryWrapper);

        List<Map<String, Object>> ruleList = baseMapper.weChatSelectInfo(groupMemberinfoId);

        Map<String, Object> map = new HashMap<>();
        map.put("cardInfo", queryInfo);
        map.put("seatinfoList", seatinfoList);
        map.put("ruleList", ruleList);

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(map);
    }

    @Override
    public ResultJson queryCardInfos(String json) {
        Map<String, String> request = JSON.parseObject(json, Map.class);
        String groupMemberinfoId = request.get("groupMemberinfoId");
        String memberGroupId = request.get("memberGroupId");
        List<String> grouplist = Arrays.asList(groupMemberinfoId.split(","));
        List<String> memberlist = Arrays.asList(memberGroupId.split(","));
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < grouplist.size(); i++) {
            String group = grouplist.get(i);
            String member = memberlist.get(i);
            if (StringUtils.isNotBlank(group) && StringUtils.isNotBlank(member)) {
                Map<String, Object> queryInfo = this.queryInfo(Long.valueOf(member), Long.valueOf(group));
                list.add(queryInfo);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(JSON.toJSON(list));
    }

    // TODO: 2019/11/12 直接延期一个月 现在需要区分其他卡类型
    //公众号延期会员，为预约会员时下发新增
    @Override
    public ResultJson deferMember(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);

        Integer buyNum = request.getBuyNum() == null ? 1 : request.getBuyNum();
        String memberinfoIds = request.getMemberinfoIds();
        String[] split = memberinfoIds.split(",");
        for (int j = 0; j < split.length; j++) {
            Long groupMemberinfoId = Long.valueOf(split[j]);
            Map<String, Object> groupByMember = baseMapper.getGroupByMember(groupMemberinfoId);
            // TODO: 2019/11/12 已查询到card_type
            Integer member_type = Integer.parseInt(groupByMember.get("member_type").toString());
            BigDecimal month_value = new BigDecimal(groupByMember.get("month_value").toString());
            BigDecimal multiply = month_value.multiply(new BigDecimal(buyNum));

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            String now = format.format(new Date());
            String new_end_date = DateUtils.getAddMonth(buyNum);

            Map<String, Object> map = new HashMap<>();
//            map.put("new_start_date", now);
//            map.put("new_end_date", new_end_date);
            map.put("buy_num", buyNum);
            map.put("operator", request.getTelNo());
            map.put("group_id", groupMemberinfoId);
            map.put("fees_roleid", groupByMember.get("feesroleinfo_id").toString());
            map.put("role_name", groupByMember.get("role_name").toString());
            map.put("amount", multiply);
            QueryWrapper<TParkGroupSeatinfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", groupMemberinfoId);
            List<TParkGroupSeatinfo> list = itParkGroupSeatinfoService.list(queryWrapper);

            //当为预约会员时更新会员表
            if (member_type.compareTo(2) == 0) {
                BigDecimal amount = multiply.multiply(new BigDecimal(list.size()));
//            if(feeAmount.compareTo(amount)!=0){
//                return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_AMOUNT_ERROR).setData(null);
//            }
                TParkGroupMemberinfo tParkGroupMemberinfo = new TParkGroupMemberinfo()
                        .setMember_type(1)
                        .setUpdateTime(Long.valueOf(DateUtils.getTime()))
                        .setStartDate(Integer.parseInt(now))
                        .setEndDate(Integer.parseInt(new_end_date))
                        .setFeeAmount(amount)
                        .setId(groupMemberinfoId);
                this.updateById(tParkGroupMemberinfo);
            }

            for (int i = 0; i < list.size(); i++) {
                map.put("id", list.get(i).getId());
                Integer endDate = list.get(i).getEndDate();
                if (endDate < Integer.valueOf(now)) {
                    map.put("new_start_date", now);
                    map.put("new_end_date", new_end_date);
                } else {
                    map.put("new_start_date", list.get(i).getStartDate());
                    String newEnd = "";
                    try {
                        newEnd = DateUtils.subMonth(list.get(i).getEndDate().toString(), buyNum);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    map.put("new_end_date", newEnd);
                }
                try {
                    log.info("deferMember:c接口请求参数,param======>" + map);
                    List<Map<String, String>> maps = kesbApiService.queryKesbApiList(Constant.MEMBER_DEFER_SEAT_CONFIRM, map);
                    log.info("deferMember:c接口返回参数,param======>" + maps);
                    if (member_type.compareTo(1) == 0) {
                        newMemberMq(String.valueOf(groupMemberinfoId), Constant.OPER_DEFER, 0, false);
                    }
                } catch (KesbException e) {
                    return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
                } catch (Exception e) {
                    log.error(Constant.ERROR_MSG_DEFER_SEAT, e);
                    throw new CustomException(Constant.ERROR_MSG_DEFER_SEAT);
                }
            }

            if (member_type.compareTo(2) == 0) {
                newMemberMq(String.valueOf(groupMemberinfoId), Constant.OPER_INSERT, 1, false);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(null);
    }


    //公众号延期会员，计算需缴费金额
    @Override
    public ResultJson getMoney(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Integer buyNum = request.getBuyNum();
        String memberinfoIds = request.getMemberinfoIds();
        String[] split = memberinfoIds.split(",");
        BigDecimal bigDecimal = new BigDecimal(0);
        for (int i = 0; i < split.length; i++) {
            Long groupMemberinfoId = Long.valueOf(split[i]);
            Map<String, Object> groupByMember = baseMapper.getGroupByMember(groupMemberinfoId);
            if (null != groupByMember) {
                BigDecimal month_value = new BigDecimal(groupByMember.get("month_value").toString());
                BigDecimal multiply = month_value.multiply(new BigDecimal(buyNum));
                QueryWrapper<TParkGroupSeatinfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("member_id", groupMemberinfoId);
                int count = itParkGroupSeatinfoService.count(queryWrapper);
                BigDecimal amount = multiply.multiply(new BigDecimal(count));
                bigDecimal = bigDecimal.add(amount);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(bigDecimal);
    }

    @Override
    public ResultJson callbackMember(String json) {
        Map<String, String> map = JSON.parseObject(json, Map.class);
        String ids = map.get("id");
        if (StringUtils.isNotBlank(ids)) {
            // TODO 1. 判断是否已经支付完成  t_trade_trans_order
            int id = Integer.valueOf(ids);
            TTradeTransOrder tradeTransOrder = tradeTraceOrderService.getById(id);
            if (null != tradeTransOrder) {
                long transState = tradeTransOrder.getTransState();
                if (transState == 3 || transState == 4) {
                    resultJson.setCode(ResultCode.REPEATCOMMIT_ERROR).setMsg(ResultCode.REPEATCOMMIT_ERROR_MSG).setData(null);
                }
                // TODO 2. 生成流水号

                // TODO 3. 更新转账信息

                // TODO 4. 插入三方流水

                // TODO 5. 生成商品订单
            } else {
                resultJson.setCode(ResultCode.NOSUCHRESULT_ERROR).setMsg(ResultCode.NOSUCHRESULT_ERROR_MSG).setData(null);
            }
        } else {
            resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG).setData(null);
        }
        return resultJson;
    }

    @Override
    public ResultJson memberPrepareOrder(String json) {
        // 1. 参数校验
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Integer buyNum = request.getBuyNum();
        String memberinfoIds = request.getMemberinfoIds();
        Long custId = request.getCustId();
        Integer payMentMethod = request.getPayMentMethod();
        String openId = request.getOpenId();
        payMentMethod = (null != payMentMethod && payMentMethod > 0) ? payMentMethod : 1;
        Integer aggregatePayflag = request.getAggregatePayflag();
        BigDecimal traceAmt = request.getFeeAmount();
        String[] split = memberinfoIds.split(",");

        // 1.1 判断是否缺少参数
        if (buyNum <= 0 || StringUtils.isBlank(memberinfoIds) || custId <= 0 || null == traceAmt) {
            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG).setData(null);
        }
        BigDecimal bigDecimal = new BigDecimal(0); // 统计总支付金额
        for (int i = 0; i < split.length; i++) {
            // 1.2 判断卡组是否存在
            Long groupMemberinfoId = Long.valueOf(split[i]);
            Map<String, Object> groupByMember = baseMapper.getGroupByMember(groupMemberinfoId);
            if (null != groupByMember) {
                // 1.3 计费是否存在 TODO 判断计费是否有效
                String feesroleinfo_id = groupByMember.get("feesroleinfo_id").toString();
                if (StringUtils.isBlank(feesroleinfo_id)) {
                    return resultJson.setCode(ResultCode.MISS_FEESROLEINFO_ERROR).setMsg(ResultCode.MISS_FEESROLEINFO_MSG).setData(null);
                }
                BigDecimal month_value = new BigDecimal(groupByMember.get("month_value").toString());
                BigDecimal multiply = month_value.multiply(new BigDecimal(buyNum));
                QueryWrapper<TParkGroupSeatinfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("member_id", groupMemberinfoId);
                int count = itParkGroupSeatinfoService.count(queryWrapper);
                BigDecimal amount = multiply.multiply(new BigDecimal(count));
                bigDecimal = bigDecimal.add(amount);

            } else {
                return resultJson.setCode(ResultCode.NOSUCHRESULT_ERROR).setMsg(ResultCode.NOSUCHRESULT_ERROR_MSG).setData(null);
            }

        }

        // 1.4 金额是否一致
        if (bigDecimal.compareTo(traceAmt) != 0) {
            return resultJson.setCode(ResultCode.PAY_MONEY_ERROR).setMsg(ResultCode.PAY_MONEY_ERROR_MSG).setData(null);
        }

        // 2. 下单
        // 2.1 查询账户资产信息
        Map<String, Object> securityAccount = baseMapper.getSecurityAccount(custId);
        Map<String, Object> aggregateInfo = baseMapper.getAggregateInfo(custId);
        String posId = "";
        String merchantId = "";
        String merchantKey = "";
        // 2.1.1 聚合支付
        if (aggregatePayflag == 1 && null != aggregateInfo && null != aggregateInfo) {
            posId = String.valueOf(aggregateInfo.get("pos_id"));
            merchantId = String.valueOf(aggregateInfo.get("merchant_id"));
            merchantKey = baseMapper.getMerchantKey(custId, merchantId, posId);
            aggregatePayflag = StringUtils.isNotBlank(merchantKey) ? 1 : 0;
        }
        // 2.2 生成预支付账单
//        QueryWrapper<TTradeTransOrder> queryWrapper = new QueryWrapper<>();
//        queryWrapper.orderByDesc("id");
//        queryWrapper.last(" limit 1");
//        List<TTradeTransOrder> idDtoList = tradeTraceOrderService.list(queryWrapper);
//        TTradeTransOrder idDto = idDtoList.get(0);
//        long newId = null != idDto ? idDto.getId() + 1 : 1;
        Long newId = null;
        try {
            newId = itSysSnogeneralService.GetNextSno(24);
        } catch (Exception e) {
            log.error("24:获取表主键异常");
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
        TTradeTransOrder transOrder = new TTradeTransOrder();
        String security_account_code = String.valueOf(securityAccount.get("security_account_code"));//security_code
        String assets_code = String.valueOf(securityAccount.get("assets_code"));//assets_code
        String trade_pwd = String.valueOf(securityAccount.get("trade_pwd"));//money_password
        transOrder.setId(newId);
        transOrder.setAssetsCode(assets_code);
        transOrder.setAssetsDigestCode(Constant.ASSETS_THIRD_CASH_PUSH);
        transOrder.setCustId(custId);
        transOrder.setFeeamt(new BigDecimal(0));
        transOrder.setMatchDatetime(0);
        transOrder.setMoneyPwd(trade_pwd);
        transOrder.setNodeId(1);
        transOrder.setOpenId(openId);//
        transOrder.setOpenidType(1);//1：微信 2：支付宝 3：小程序
        Long time = System.currentTimeMillis();
        Date now = new Date(time);
        String nowStr = DateUtils.getTimeString(DateUtils.YYYYMMDDHHMMSS, now);
        transOrder.setOrderDatetime(Long.valueOf(nowStr));//
        transOrder.setPaymentMethod(payMentMethod);
        transOrder.setRemark("");
        transOrder.setResultMsg(Constant.MSG_PAY_MONTH);
        transOrder.setSecId(Long.valueOf(security_account_code));
        transOrder.setSerialno("");
        transOrder.setTargetAssetsCode("");
        transOrder.setTargetCustId(0);
        transOrder.setTargetSecId(0);
        transOrder.setThirdId(0);
        transOrder.setTransamt(traceAmt);
//        int a = (int) (Math.random() * 10000000 + 1);
//        String transCode = merchantId + DateUtils.getNowString(DateUtils.YYYYMMDD) + a;// TODO: 2019/12/11 生成规则待确定

        String prefix = DateUtils.getNowString(DateUtils.YYYYMMDD) + String.valueOf(custId) + "1";
        String transCode = "";
        try {
            transCode = itSysSnogeneralService.GetNextPrefix(121, prefix) + "T";
        } catch (Exception e) {
            log.error(prefix + ":获取订单序列异常");
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

        transOrder.setTransCode(transCode);// TODO 规则生成 聚合支付规则  merchant_id+日期
        transOrder.setTransDirection(1);// 1 转入 2 转出 3 系统内部
        transOrder.setTransState(1);// 1 初始 3 失败 4 成功
        Long addTime = time + 30 * 1000 * 60;
        Date validTime = new Date(addTime);
        String validStr = DateUtils.getTimeString(DateUtils.YYYYMMDDHHMMSS, validTime);
        transOrder.setValidDatetime(Long.valueOf(validStr));
        boolean flag = tradeTraceOrderService.save(transOrder);
        if (!flag) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        } else {
//            TTradeTransOrder resp = tradeTraceOrderService.getById(newId);
            Map<String, Object> map = new HashMap<>();
            map.put("transCode", transCode);
            map.put("id", newId);
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(map);
        }
    }

    @Override
    public ResultJson getMemberGroup(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        QueryWrapper<TParkMemberGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_code", request.getParkCode());
        queryWrapper.eq("del_flag", 0);
        queryWrapper.eq("type", 1);
        queryWrapper.eq("classify", 5);
        queryWrapper.ne("id", request.getMemberGroupId());
        queryWrapper.orderByAsc("classify");
        queryWrapper.orderByAsc("create_time");
        List<TParkMemberGroup> list = itParkMemberGroupService.list(queryWrapper);

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
    }

    @Override
    public ResultJson queryMemberRecord(String json) {
        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
        Page page = new Page<>(request.getPageSize(), request.getPageNo());
        if (request.getType() == 0) {
            //缴费记录
            page = itCarMemberamountinfoService.getAmountInfo(request.getPageSize(), request.getPageNo(), request.getGroupMemberinfoId());

        } else if (request.getType() == 1) {
            //操作记录
            QueryWrapper<TParkGroupOperateLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id", request.getGroupMemberinfoId());
            queryWrapper.eq("operate_type", 10);
            queryWrapper.orderByAsc("operate_time");
            List<TParkGroupOperateLog> list = itParkGroupOperateLogService.list(queryWrapper);

            TParkGroupMemberinfo byId = this.getById(request.getGroupMemberinfoId());
            List<Map<String, Object>> recordResponses = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String remark = list.get(i).getRemark();
                String operatorNo = list.get(i).getOperatorNo();
                String operateTime = list.get(i).getOperateTime().toString();
                QueryWrapper<TAcctCustInfo> acctCustInfoQueryWrapper = new QueryWrapper<>();
                acctCustInfoQueryWrapper.eq("cust_id", operatorNo);
                TAcctCustInfo tAcctCustInfo = itAcctCustInfoService.getOne(acctCustInfoQueryWrapper);

                String[] split = remark.split(",");
                String carType = split[1].split(":")[1];
                RecordResponse recordResponse = new RecordResponse();
                recordResponse.setName(byId.getOwnerName());
                recordResponse.setOperName(tAcctCustInfo.getName());
                recordResponse.setOperInfo(remark.substring(0, 4));
                recordResponse.setCarId(split[0].split(":")[1]);
                recordResponse.setCarType(getCarTypeStr(carType));
                try {
                    recordResponse.setOperDate(operateTime.substring(0, 4) + "-" + operateTime.substring(4, 6) + "-" + operateTime.substring(6, 8) + " " + operateTime.substring(8, 10) + ":" + operateTime.substring(10, 12) + ":" + operateTime.substring(12, 14));
                } catch (Exception e) {
                    recordResponse.setOperDate("-");
                }
                Map<String, Object> recordResponseMap = beanToMap(recordResponse);
                recordResponses.add(recordResponseMap);
            }

            page = byPage(request.getPageNo(), request.getPageSize(), recordResponses);
        } else {
            //暂停启用记录
            page = itCarMemberamountinfoService.getStopRecord(request.getPageSize(), request.getPageNo(), request.getGroupMemberinfoId());
        }

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
    }

    @Override
    public ResultJson syncMemberInfo(String json) {
        try {
            Map map = JSON.parseObject(json, Map.class);
            String parkCode = map.get("parkCode").toString();
//        MemberinfoMqDto memberinfoMqDto = ne
//       TParkMemberGroupRelationDto
            //查询当前停车场的会员
            if (StringUtils.isNotBlank(parkCode)) {

                SyncMemberDto syncMemberDtos = new SyncMemberDto(); //最后返回的结果集
                List<MemberinfoMqDto> memberinfoMqDtos = new ArrayList<>(); //会员结果集
                List<TParkMemberGroupRelationDto> relationDtos = new ArrayList<>();//会员卡组关联表结果集


                QueryWrapper<TParkGroupMemberinfo> memberinfoQueryWrapper = new QueryWrapper<>();
                memberinfoQueryWrapper.eq("park_code", parkCode).orderByAsc("create_time");
                List<TParkGroupMemberinfo> memberList = this.list(memberinfoQueryWrapper);
                for (TParkGroupMemberinfo memberinfo : memberList) {
                    //查询车位信息表
                    Long memberId = memberinfo.getId(); //会员id

                    QueryWrapper<TParkGroupCarinfo> carinfoQueryWrapper = new QueryWrapper<>();
                    carinfoQueryWrapper.eq("group_id", memberId).orderByAsc("create_time");

                    List<TParkGroupCarinfo> carinfoList = itParkGroupCarinfoService.list(carinfoQueryWrapper);
                    for (TParkGroupCarinfo carinfo : carinfoList) {
                        //下发白名单信息
                        MemberinfoMqDto memberinfoMqDto = new MemberinfoMqDto();
                        memberinfoMqDto.setCar_id(carinfo.getCarId());
                        memberinfoMqDto.setCar_type(carinfo.getCarType().toString().replaceAll("8", "5"));
                        memberinfoMqDto.setEnd_date(memberinfo.getEndDate().toString());
                        memberinfoMqDto.setGroup_id(memberId.toString());
                        memberinfoMqDto.setId(String.valueOf(carinfo.getId()));
                        //todo ? 待确定
                        memberinfoMqDto.setMember_type(Constant.MEMBER_TYPE_WHITE);
                        memberinfoMqDto.setOper_type(Constant.OPER_CAR);
                        memberinfoMqDto.setOwner_name(memberinfo.getOwnerName());
                        memberinfoMqDto.setPark_code(memberinfo.getParkCode());
                        memberinfoMqDto.setRemark(memberinfo.getRemark());
                        memberinfoMqDto.setSeat_num(String.valueOf(carinfoList.size()));
                        memberinfoMqDto.setSend_time(DateUtils.getTime());
                        memberinfoMqDto.setStart_date(memberinfo.getStartDate().toString());
                        memberinfoMqDtos.add(memberinfoMqDto);
                    }

                    QueryWrapper<TParkMemberGroupRelation> relationQueryWrapper = new QueryWrapper<>();
                    relationQueryWrapper.eq("member_id", memberId).orderByAsc("create_time");
                    List<TParkMemberGroupRelation> list = itParkMemberGroupRelationService.list(relationQueryWrapper);
                    if (!CollectionUtils.isEmpty(list)) {
                        List<TParkMemberGroupRelationDto> collect = list.parallelStream().filter(Objects::nonNull)
                                .map(TParkGroupMemberinfoServiceImpl::apply).collect(Collectors.toList());
                        relationDtos.addAll(collect);
                    }
                }
                syncMemberDtos.setMembers(memberinfoMqDtos);
                syncMemberDtos.setMemberGroupRelations(relationDtos);
                return resultJson.setCode(ResultCode.SUCCESS)
                        .setMsg(ResultCode.SUCCESS_MSG)
                        .setData(syncMemberDtos);
            }
            return resultJson.setCode(ResultCode.SUCCESS)
                    .setMsg(ResultCode.SUCCESS_MSG)
                    .setData(null);
        } catch (Exception e) {
            log.error("error", e);
            return resultJson.setCode(ResultCode.FAIL)
                    .setMsg(ResultCode.FAIL_MSG)
                    .setData(null);
        }
    }

    /**
     * 查询柜台信息
     *
     * @param json
     * @return
     */
    @Override
    public ResultJson selectBankInfo(String json) {
        TAcctBankMerchantInfo request = JSON.parseObject(json, TAcctBankMerchantInfo.class);
        if (null == request) {
            return resultJson.setCode(ResultCode.FAIL).setMsg("找不到商户信息").setData(null);
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(bankMerchantInfoMapper.selectBankInfo(request.getAgentId()));
    }

    /**
     * 更新会员当月累计额度
     *
     * @param param
     * @return ResultJson
     */
    @Override
    public ResultJson updateMemAccAmt(Map<String, String> param) {
        try {
            Long assetsId = Long.valueOf(param.get("assetsId"));
            BigDecimal accumulateAmt = new BigDecimal(param.get("accumulateAmt"));
            TParkGroupMemberinfo tParkGroupMemberinfo = new TParkGroupMemberinfo();
            tParkGroupMemberinfo.setId(assetsId);
            tParkGroupMemberinfo.setAccumulateAmt(accumulateAmt);
            boolean res = this.updateById(tParkGroupMemberinfo);
            if (res) {
                return new ResultJson().setCode(ResultCode.SUCCESS)
                        .setMsg(ResultCode.SUCCESS_MSG).setData(true);
            } else {
                return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(false);
            }
        } catch (Exception e) {
            log.error("error", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(false);
        }
    }


    private static TParkMemberGroupRelationDto apply(TParkMemberGroupRelation source) {
        TParkMemberGroupRelationDto target = new TParkMemberGroupRelationDto();
        BeanUtils.copyProperties(source, target);
        target.setType(1);
        return target;
    }

    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    public void newMemberMq(String member_info_id, String operType, int type, boolean delSeat) {
        TParkGroupMemberinfo member_info = this.getById(member_info_id);
        QueryWrapper<TParkGroupSeatinfo> qw1 = new QueryWrapper<>();
        qw1.eq("member_id", member_info_id);
        qw1.eq("car_state", 1);
        int count = itParkGroupSeatinfoService.count(qw1);
        QueryWrapper<TParkGroupCarinfo> qw = new QueryWrapper<>();
        qw.eq("group_id", member_info_id);
        qw.eq("delflag", 1);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(new Date());
        MemberinfoMqDto dto = null;
        if (delSeat) {
            dto = new MemberinfoMqDto();
            dto.setEnd_date(member_info.getEndDate().toString());
            dto.setGroup_id(member_info_id);
            dto.setMember_type(Constant.MEMBER_TYPE_NEW);
            dto.setOper_type(operType);
            dto.setOwner_name(member_info.getOwnerName());
            dto.setPark_code(member_info.getParkCode());
            dto.setRemark(member_info.getRemark() == null ? "" : member_info.getRemark());
            dto.setSeat_num(String.valueOf(count));
            dto.setSend_time(now);
            dto.setStart_date(member_info.getStartDate().toString());
            mqService.mqSend(JSON.toJSONString(dto), "member." + member_info.getParkCode());
        } else {
            List<TParkGroupCarinfo> list = itParkGroupCarinfoService.list(qw);
            for (int i = 0; i < list.size(); i++) {
                //下发白名单信息
                dto = new MemberinfoMqDto();
                dto.setCar_id(list.get(i).getCarId());
                dto.setCar_type(list.get(i).getCarType().toString().replaceAll("8", "5"));
                dto.setEnd_date(member_info.getEndDate().toString());
                dto.setGroup_id(member_info_id);
                //carinfo id
                dto.setId(list.get(i).getId().toString());
                dto.setMember_type(Constant.MEMBER_TYPE_NEW);
                dto.setOper_type(operType);
                dto.setOwner_name(member_info.getOwnerName());
                dto.setPark_code(member_info.getParkCode());
                dto.setRemark(member_info.getRemark() == null ? "" : member_info.getRemark());
                dto.setSeat_num(String.valueOf(count));
                dto.setSend_time(now);
                dto.setStart_date(member_info.getStartDate().toString());
                mqService.mqSend(JSON.toJSONString(dto), "member." + member_info.getParkCode());
            }
        }


        if (type != 0) {
            QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("member_id", member_info_id);
            TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
            TParkMemberGroupRelationDto tParkMemberGroupRelationDto = DtoUtil.convertObject(one, TParkMemberGroupRelationDto.class);
            tParkMemberGroupRelationDto.setType(type);
            //下发关系表
            mqService.mqSend(JSON.toJSONString(tParkMemberGroupRelationDto), "memberGroupRelation." + member_info.getParkCode());

        }
    }

    private String getCarTypeStr(String carType) {
        String carTypeStr = "";
        switch (carType) {
            case "1":
                carTypeStr = "蓝牌车";
                break;
            case "2":
                carTypeStr = "中型车";
                break;
            case "3":
                carTypeStr = "黄牌车";
                break;
            case "4":
                carTypeStr = "电动车";
                break;
            case "6":
                carTypeStr = "绿牌车";
                break;
            case "7":
                carTypeStr = "白牌车";
                break;
            case "8":
                carTypeStr = "黑牌车";
                break;
            default:
                carTypeStr = "";
                break;
        }
        return carTypeStr;
    }


//    @Override
//    public ResultJson memberPrepareOrder(String json) {
//        // 1. 参数校验
//        TParkGroupMemberinfoRequest request = JSON.parseObject(json, TParkGroupMemberinfoRequest.class);
//        Integer buyNum = request.getBuyNum();
//        String memberinfoIds = request.getMemberinfoIds();
//        Long custId = request.getCustId();
//        Integer payMentMethod = request.getPayMentMethod();
//        String openId = request.getOpenId();
//        payMentMethod = (null != payMentMethod && payMentMethod > 0) ? payMentMethod : 1;
//        Integer aggregatePayflag = request.getAggregatePayflag();
//        BigDecimal traceAmt = request.getFeeAmount();
//        String[] split = memberinfoIds.split(",");
//
//        // 1.1 判断是否缺少参数
//        if (buyNum <= 0 || StringUtils.isBlank(memberinfoIds) || custId <= 0 || null == traceAmt) {
//            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG).setData(null);
//        }
//        BigDecimal bigDecimal = new BigDecimal(0); // 统计总支付金额
//        for (int i = 0; i < split.length; i++) {
//            // 1.2 判断卡组是否存在
//            Long groupMemberinfoId = Long.valueOf(split[i]);
//            Map<String, Object> groupByMember = baseMapper.getGroupByMember(groupMemberinfoId);
//            if (null != groupByMember) {
//                // 1.3 计费是否存在 TODO 判断计费是否有效
//                String feesroleinfo_id = groupByMember.get("feesroleinfo_id").toString();
//                if (StringUtils.isBlank(feesroleinfo_id)) {
//                    return resultJson.setCode(ResultCode.MISS_FEESROLEINFO_ERROR).setMsg(ResultCode.MISS_FEESROLEINFO_MSG).setData(null);
//                }
//                BigDecimal month_value = new BigDecimal(groupByMember.get("month_value").toString());
//                BigDecimal multiply = month_value.multiply(new BigDecimal(buyNum));
//                QueryWrapper<TParkGroupSeatinfo> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("member_id", groupMemberinfoId);
//                int count = itParkGroupSeatinfoService.count(queryWrapper);
//                BigDecimal amount = multiply.multiply(new BigDecimal(count));
//                bigDecimal = bigDecimal.add(amount);
//
//
//            } else {
//                return resultJson.setCode(ResultCode.NOSUCHRESULT_ERROR).setMsg(ResultCode.NOSUCHRESULT_ERROR_MSG).setData(null);
//            }
//
//        }
//
//        // 1.4 金额是否一致
//        if (bigDecimal.compareTo(traceAmt) != 0) {
//            return resultJson.setCode(ResultCode.PAY_MONEY_ERROR).setMsg(ResultCode.PAY_MONEY_ERROR_MSG).setData(null);
//        }
//
//        // 2. 下单
//        // 2.1 查询账户资产信息
//        Map<String, Object> aggregateInfo = baseMapper.getAggregateInfo(custId);
//        String posId = "";
//        String merchantId = "";
//        String merchantKey = "";
//        // 2.1.1 聚合支付
//        if (aggregatePayflag == 1 && null != aggregateInfo && null != aggregateInfo) {
//            posId = String.valueOf(aggregateInfo.get("pos_id"));
//            merchantId = String.valueOf(aggregateInfo.get("merchant_id"));
//            merchantKey = baseMapper.getMerchantKey(custId, merchantId, posId);
//            aggregatePayflag = StringUtils.isNotBlank(merchantKey) ? 1 : 0;
//        }
//        // 2.2 生成预支付账单
//
//
//        Map<String, Object> createOrderMap = new HashMap<>();
//        createOrderMap.put("cust_id", custId);
//        createOrderMap.put("car_id", request.getCarId());
//        createOrderMap.put("car_type", request.getCarType());
//        //createOrderMap.put("feesrole_id", feesroleinfo_id);
//        createOrderMap.put("payment_method", payMentMethod);
//        createOrderMap.put("transamt", traceAmt);
//        createOrderMap.put("feeamt", "0.00");
//        createOrderMap.put("aggregate_payflag", aggregatePayflag);
//        createOrderMap.put("openid", openId);
//        createOrderMap.put("source",0 );// TODO: 2019/12/9   0微信 1小程序 2支付宝
//
//        try {
//            log.info("memberPrepareOrder:c接口请求参数,param======>" + createOrderMap);
//            Map<String, String> map = kesbApiService.queryKesbApi(Constant.API_BUY_MONTH_ORDER, createOrderMap);
//            log.info("memberPrepareOrder:c接口返回参数,param======>" + map);
//            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(map);
//        } catch (KesbException e) {
//            return resultJson.setCode(ResultCode.FAIL).setMsg(e.getMessage()).setData(null);
//        } catch (Exception e) {
//            log.error(Constant.ERROR_MSG_Prepare_Order, e);
//            throw new CustomException(Constant.ERROR_MSG_Prepare_Order);
//        }
//
//    }

}
